var ctx;
var firstLevel = 1;
var secondLevel = 2;
var firstCategory = '';
var secondCategory = '';

function setCtx(ctx) {
	this.ctx = ctx;
	initListener();  //添加区域监听事件
}

//省市区级联
function initListener() {
	$("#firstCategory").change(function () {
		firstCategory = $('#firstCategory').val();
		if (firstCategory != '') {
			$.ajax({
		        type : "GET",
		        url : ctx + "/goods/getCategoryByParentId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	parentId : firstCategory
		        },
		        success : function(data) {
		        	if (data.success) {
		                var result = "<option value='" + "'>--二级分类--</option>";
		                $.each(data.obj, function(index, item) {
		                    result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
		                });
		                $("#secondCategory").html('');
		                $("#secondCategory").append(result);
		            }
		        }
			});
		} else {
			var result = "<option value='" + "'>--二级分类--</option>";
			$("#secondCategory").html('');
            $("#secondCategory").append(result);
		}
    });
	
    $('#secondCategory').change(function() {
    	if ($('#secondCategory').val() != 0) {
    		secondCategory = $('#secondCategory').val();
    		if(secondCategory != ''){
    			$.ajax({
    				type : "POST",
    				url : ctx + "/goodsInfo/getGoodsAttrByCategoryId",
    				cache : false,
    				dataType : 'json',
    				data : {
    					categoryId : secondCategory
    				},
    				success : function(data) {
    					if (data.success) {
    					      var jsonObj=eval("("+data.obj+")");  
    					      
    					      var html = "<table style='width:100%; margin-top:0px;table-layout:fixed'><tbody><tr>";
    					        $.each(jsonObj, function (i, item) {
    					        	html += "<input id='attrId"+item.id+"' type='hidden' value="+item.id+" >";
    					        	html += "<th width='10%' style='background-color: #e0eff3;height:40px'>"+item.name+"</th>";
    					        });
    					        html += "<tr></tbody>";
    					        html += "<tbody id='tableTbody'>";
    					        html += "<tr>";
	    					        $.each(jsonObj, function (i, item) {
	    					        	if(item.inputType == 1){
	    					        		html += "<td><select class='editform-control' style='height: 31px;'>";
		    					        	for(var j = 0;j < item.categoryAttrValues.length;j++){
		    					        			html += "<option value="+item.categoryAttrValues[j].id+">"+item.categoryAttrValues[j].name+"</option>";
		    					        			
		    					        	}
		    					        	html += "</select></td>";
	    					        	}else if(item.inputType == 2){
	    					        		html += "<td><input class='controlEdit' type='text' maxlength='50' value='11' ></td>";
	    					        	}
	    					        });
    					        html += "</tr>";
    					        html += "</tbody></table>";
    					        $("#goodsSpecification").append(html);
    					}
    				}
    			});
    		}
    	}
    });

}


function showdelete(target){
	$(target).children("span").css("display","block");
}

function hidedelete(target){
	$(target).children("span").css("display","none");
}

function gotoGoodsInfo(target){
	$("#goodsInfo")[0].style.display="block";
	$("#goodsDescrip")[0].style.display="none";
	$("#goodsSpec")[0].style.display="none";
	$("#selected1").attr("src",ctx+"/images/seller/coupon/select_yellow.png");
	$("#selected2").attr("src",ctx+"/images/seller/coupon/select_blue.png");
	$("#selected3").attr("src",ctx+"/images/seller/coupon/select_blue.png");
}

function gotoGoodsDescrip(target){
	$("#goodsDescrip")[0].style.display="block";
	$("#goodsInfo")[0].style.display="none";
	$("#goodsSpec")[0].style.display="none";
	$("#selected2").attr("src",ctx+"/images/seller/coupon/select_yellow.png");
	$("#selected1").attr("src",ctx+"/images/seller/coupon/select_blue.png");
	$("#selected3").attr("src",ctx+"/images/seller/coupon/select_blue.png");
}

function gotoGoodsSpec(target){
	$("#goodsSpec")[0].style.display="block";
	$("#goodsDescrip")[0].style.display="none";
	$("#goodsInfo")[0].style.display="none";
	$("#selected3").attr("src",ctx+"/images/seller/coupon/select_yellow.png");
	$("#selected1").attr("src",ctx+"/images/seller/coupon/select_blue.png");
	$("#selected2").attr("src",ctx+"/images/seller/coupon/select_blue.png");
}

function checkStartTime(){
	var startTime = $("#startTime").val();
	//解决ie9以下placeholder与value重复的问题
	if(startTime == $("#startTime").attr("placeholder")){
		startTime = "";
	}
	
    var	start = new Date(startTime.replace("-", "/").replace("-", "/"));
    if(startTime == null || startTime == ""){
		layer.tips('秒杀开始时间不能为空!', '#startTime', {
		    tips: 3
		});
		return false;
    }else{
		return true;    	
    }
}

function checkEndTime(){
	var startTime = $("#startTime").val();
    var	start = new Date(startTime.replace("-", "/").replace("-", "/")); 
    var endTime = $("#endTime").val();
    var	end = new Date(endTime.replace("-", "/").replace("-", "/")); 
    //解决ie9以下placeholder与value重复的问题
	if(startTime == $("#startTime").attr("placeholder")){
		startTime = "";
	}
	if(endTime == $("#endTime").attr("placeholder")){
		endTime = "";
	}
	if(endTime == null || endTime == ""){
		layer.tips('秒杀结束时间不能为空!', '#endTime', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else if(end < start){
    	layer.msg("结束时间应大于起始时间",{
			icon: 3,
			time: 1000 //2秒关闭（如果不配置，默认是3秒）
		});
    	return false;
	}else{
		return true;
	}
}

function checkGoodsName(){
	var goodsName = $("#goodsName").val();
	//解决ie9以下placeholder与value重复的问题
	if(goodsName == $("#goodsName").attr("placeholder")){
		goodsName = "";
	}
	if(goodsName == null || goodsName == ""){
		layer.tips('请填写商品名称!', '#goodsName', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else{
		return true;
	}
}

function checkGoodsCategaryOne(){
	var firstCategory = $("#firstCategory").val();
	//解决ie9以下placeholder与value重复的问题
	if(firstCategory == $("#firstCategory").attr("placeholder")){
		firstCategory = "";
	}
	if(firstCategory == null || firstCategory == ""){
		layer.tips('请选择一级分类!', '#firstCategory', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else{
		return true;
	}
}

function checkGoodsCategaryTwo(){
	var secondCategory = $("#secondCategory").val();
	//解决ie9以下placeholder与value重复的问题
	if(secondCategory == $("#secondCategory").attr("placeholder")){
		secondCategory = "";
	}
	if(secondCategory == null || secondCategory == ""){
		layer.tips('请选择二级分类!', '#secondCategory', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else{
		return true;
	}
}

function checkPrice(){
	var businessPrice = $("#businessPrice").val();
	//解决ie9以下placeholder与value重复的问题
	if(businessPrice == $("#businessPrice").attr("placeholder")){
		businessPrice = "";
	}
	if(businessPrice == null || businessPrice == ""){
		layer.tips('请填写价格!', '#businessPrice', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else if(parseInt(businessPrice) < 0){
		layer.tips('价格不能小于0!', '#businessPrice', {
		    tips: 3,
		    time:1000
		});
		return false;
	} else {
		return true;
	}
}

function checkMarketPrice(){
	var marketPrice = $("#marketPrice").val();
	//解决ie9以下placeholder与value重复的问题
	if(marketPrice == $("#marketPrice").attr("placeholder")){
		marketPrice = "";
	}
	if(marketPrice == null || marketPrice == ""){
		layer.tips('请填写市场价!', '#marketPrice', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else if(parseInt(marketPrice) < 0){
		layer.tips('市场价不能小于0!', '#marketPrice', {
		    tips: 3,
		    time:1000
		});
		return false;
	} else {
		return true;
	}
}

function checkUnit(){
	var unit = $("#unit").val();
	//解决ie9以下placeholder与value重复的问题
	if(unit == $("#unit").attr("placeholder")){
		unit = "";
	}
	if(unit == null || unit == ""){
		layer.tips('请填写单位!', '#unit', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else{
		return true;
	}
}

function checkRecommendLevel(){
	var recommendLevel = $("#recommendLevel").val();
	//解决ie9以下placeholder与value重复的问题
	if(recommendLevel == $("#recommendLevel").attr("placeholder")){
		recommendLevel = "";
	}
	if(parseInt(recommendLevel) < 0){
		layer.tips('请填写大于0的数字!', '#recommendLevel', {
		    tips: 3,
		    time:1000
		});
		$("#recommendLevel").val("");
		return false;
	} else {
		return true;
	}
}

//保存或新增方法
function saveGoodsInfo() {
	var infoList = getSpecValues();
//	var goodsName = $('#goodsName').val();
//	var secondCategory = $('#secondCategory').val();
//	var businessPrice = $("#businessPrice").val();
//	var marketPrice = $("#marketPrice").val();
//	var unit = $("#unit").val();
//	var keyword = $("#keyword").val();
//	var isRecommend = $("#recommendLevel").val();
//	var sort = $('#sort').val();
//	var goodsId;
//	if($('#goodsId').val() != "" && $('#goodsId').val() != undefined){
//		goodsId = $('#goodsId').val();
//	}else{
//		goodsId = 0;
//	}
//	var container = ue.getContent();
//	var imageLogoUrl = $('#imageLogo').val();
//	//解决ie9以下placeholder与value重复的问题
//	if(goodsName == $("#goodsName").attr("placeholder")){
//		goodsName = "";
//	}
//	if(keyword == $("#keyword").attr("placeholder")){
//		keyword = "";
//	}
//	var vals = [];
//	vals = keyword.split('|');
//	var length = $("#imgLength").val();
//	var imgArr = [];
//	for(var i=1;i <= length;i++){
//		if($("#imgId" + i).val() != null){
//			imgArr.push($("#imgId" + i).val());
//		}
//	}
//	var keywordArr = vals.join(',');//转换为逗号隔开的字符串 
	if(checkGoodsName() && checkGoodsCategaryOne() && checkGoodsCategaryTwo()
			&& checkPrice() && checkMarketPrice() && checkUnit()){
		$.ajax({
			type : "POST",
			url : ctx + "/goods/saveOrUpdateGoodsInfo",
			cache : false,
			dataType : 'json',
			contentType : 'application/json;charset=utf-8', //设置请求头信息
			data:JSON.stringify(infoList),
//				data: {
//					goodsName : goodsName,
//					secondCategory : secondCategory,
//					price : businessPrice,
//					marketPrice : marketPrice,
//					unit : unit,
//					keyword : keywordArr,
//					isRecommend : isRecommend,
//					sort : sort,
//					goodsId : goodsId,
//					container : container,
//					imageLogoUrl : imageLogoUrl,
//					imgArr : imgArr
//				},
			success : function(result) {
				if (result.success) {
					//alert("操作成功");
					
					layer.msg("操作成功",{
						icon: 1,
						time: 3000 //2秒关闭（如果不配置，默认是3秒）
					},function(){
							clickFirstMenu(100146355164006600);
					});
				} else {
					layer.msg("操作失败",{
						icon: 2
					});
				}
			}
		});
		
	}
}

function showDefineAttr(){
	$("#defineAttr").toggle();
}

function hideDefineAttr(){
	$("#defineAttr").hide();
}

//返回上一页
function cancel(){
	loadContent("/goods/goodsInfoList");
}

function appendRow(){
	var firstRow = $('#attr_spec tr:eq(0)');
	var appendTd = '';
	if(firstRow.length == 0 ) {
		appendTd += '<td><input type="text" class="add-input"></td>'+
			'<td><input type="text" class="add-input" ></td>';
	} else {
		var firstRowTds = $('#attr_spec tr:eq(0) td');
		for(var i = 0; i < firstRowTds.length; i++) {
//			appendTd = appendTd + '<td><input type="text"class="add-input"  ></td>';
			if( i == firstRowTds.length - 1) {
				appendTd += '<td><input type="button" value="删除" onclick="deleteRow(this);" class="delete-btn"/></td>';
			} else if(i == firstRowTds.length - 2) {
//				appendTd += '<td><input type="button" value="上传图片" onclick="" style="width:80px;"/></td>';
				appendTd += '<td><input type="text" name="stock" style="width:80px;"/></td>';
			} else if(i == firstRowTds.length - 3) {
				appendTd += '<td><input type="text" name="price" style="width:80px;"/></td>';
//				appendTd += '<td><input type="text" name="stock" style="width:80px;"/></td>';
//			} else if(i == firstRowTds.length - 4) {
//				appendTd += '<td><input type="text" name="price" style="width:80px;"/></td>';
			} else {
				appendTd += '<td><input type="text"  class="add-input"></td>';
			}
		}
	}
	$('#attr_spec').append('<tr>' + appendTd + '</tr>');
}

var attrNames = [];
function appendCloumn(){
//	$("#attr_spec tr:eq(0)").before('<tr><td><input type="text" style="width:80px;"></td></tr>');
	var attrName = $('#attr_name').val();
	var src = ctx + "/images/del.png"
	if('' != attrName) {
		$('#attr_spec').find('tr').each(function(index){
			if(index == 0) {
				attrNames.push(attrName);
				$(this).prepend('<td class="bg-td" width="150px">'  + attrName + "<img id='close' src='images/guanbi.png' onclick='delete_cloum(this);' >" + '</td>');
			} else {
				$(this).prepend('<td ><input type="text" class="add-input"></td>');
			}
		});
	}
	
}

function delete_cloum(target){
	var current_td=$(target).parent()
	var index=current_td.index();
	$('#attr_spec').find('tr').each(function(){
		$(this).children().eq(index).remove();
	})
}

function deleteRow(target){
	$(target).parent().parents('tr').remove();
}

function getSpecValues(){
	var goodsName = $('#goodsName').val();
	var secondCategory = $('#secondCategory').val();
	var businessPrice = $("#businessPrice").val();
	var marketPrice = $("#marketPrice").val();
	var unit = $("#unit").val();
	var keyword = $("#keyword").val();
	var isRecommend = $("#recommendLevel").val();
	var sort = $('#sort').val();
	var goodsId;
	if($('#goodsId').val() != "" && $('#goodsId').val() != undefined){
		goodsId = $('#goodsId').val();
	}else{
		goodsId = 0;
	}
	var container = ue.getContent();
	var imageLogoUrl = $('#imageLogo').val();
	//解决ie9以下placeholder与value重复的问题
	if(goodsName == $("#goodsName").attr("placeholder")){
		goodsName = "";
	}
	if(keyword == $("#keyword").attr("placeholder")){
		keyword = "";
	}
	var vals = [];
	vals = keyword.split('|');
	var length = $("#imgLength").val();
	var imgArr = [];
	for(var i=1;i <= length;i++){
		if($("#imgId" + i).val() != null){
			imgArr.push($("#imgId" + i).val());
		}
	}
	var keywordArr = vals.join(',');//转换为逗号隔开的字符串 
	
	var firstRow = $('#attr_spec tr:eq(0) td');
	var initCol = 3;
	var realClo = firstRow.length;
	
	var specs = new Array();
	$('#attr_spec').find('tr:not(:first)').each(function(){
//	$('#attr_spec').find('tr').each(function(rowIndex){
		var info = {};
		
		info.goodsName = goodsName;
		info.secondCategory = secondCategory;
		info.price = businessPrice;
		info.marketPrice = marketPrice;
		info.unit = unit;
		info.keyword = keywordArr;
		info.isRecommend = isRecommend;
		info.sort = sort;
		info.goodsId = goodsId;
		info.container = container;
		info.imageLogoUrl = imageLogoUrl;
		info.imgArr = imgArr;
		
		$(this).find('td input').each(function(index){
			var flag = firstRow.length - initCol;
			if(flag > 0 && index < flag){
				switch (index) {
				case 0:
					info.attr1 = attrNames[0]
					info.attr1Value = this.value;
					break;
				case 1:
					info.attr2 = attrNames[1]
					info.attr2Value = this.value
					break;
				case 2:
					info.attr3 = attrNames[2]
					info.attr3Value = this.value
					break;
				default:
					break;
				}
			}
		});
		info.price = $(this).find('input[name="price"]').val();
		info.stock = $(this).find('input[name="stock"]').val();
		specs.push(info);
	});
	return specs;
}

//返回上一页
function cancel(){
	loadContent("/main");
}
